package com.efounder.message.model;

import com.efounder.constant.EnvironmentVariable;
import com.efounder.message.manager.JFMessageManager;
import com.efounder.message.struct.IMStruct002;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MessageModel {
    private List<IMStruct002> list = new ArrayList<IMStruct002>();
    private Map<String, IMStruct002> map = new HashMap<String, IMStruct002>();
    private int unReadCount;
    private int userType;
    private String userID;
    private IMStruct002 lastMessage;
    private String atMessageID = "";

    public MessageModel() {
    }

    public void add(IMStruct002 message) {
        int index = list.size();
        this.add(message, index);
    }

    public void add(IMStruct002 message, int index) {
        list.add(index, message);
        map.put(message.getMessageID(), message);
        if (message.getFromUserId() != Integer.parseInt(EnvironmentVariable.getUserID())
                && (message.getState() == IMStruct002.MESSAGE_STATE_UNREAD || message.getState() == -1)) {
            this.messageUnread(message);
        }

        //判断是否是at我的消息
        if (isAtMeMessage(message)) {
            atMessageID = message.getMessageID();
        }
//		if(lastMessage == null){
//			lastMessage = message;
//		}else if(lastMessage.getLocalTime() < message.getLocalTime()){
//			lastMessage = message;
//		}
        lastMessage = message;
        updateSelfToDB();
    }

    /**
     * 是否是@我的消息
     *
     * @param imStruct002
     * @return
     */
    private boolean isAtMeMessage(IMStruct002 imStruct002) {
        if (imStruct002.getMessageChildType() != 11) {
            return false;
        }
        String messageText = imStruct002.getMessage();
        try {
            net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(messageText);
            String type = jsonObject.optString("type", "");
            if ("at".equals(type)) {
                JSONArray array = jsonObject.getJSONArray("ID");
                int myUserId = Integer.valueOf(EnvironmentVariable.getUserID());
                for (int i = 0; i < array.size(); i++) {
                    JSONObject item = array.getJSONObject(i);
                    if (item.optInt("userId", 0) == myUserId) {
                        return true;
                    }
                }
            } else {
                return false;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public void clearAtMe() {
        this.atMessageID = "";
        updateSelfToDB();
    }

    /**
     * 获取@消息所在位置
     *
     * @return
     */
    public int getAtMessageIndex() {
        if (atMessageID.equals("")) {
            return -1;
        }
        return getMessageIndex(atMessageID);
    }

    /**
     * 获取消息在数组中的位置
     *
     * @param messageID
     * @return
     */
    public int getMessageIndex(String messageID) {
        IMStruct002 imStruct002 = map.get(messageID);
        if (imStruct002 == null) {
            return -1;
        } else {
            return list.indexOf(imStruct002);
        }
    }

    public IMStruct002 get(String key) {
        return map.get(key);
    }

    public void remove(IMStruct002 message) {
        if (map.get(message.getMessageID()) == null) return;
        list.remove(message);
        map.remove(message.getMessageID());
        //如果该消息为最后一条消息 取上一条
        //fixme yqs  message == getLastMessage() 重新打开应用不是同一个对象，应该比较消息id
//		if (message == getLastMessage() && list.size() > 0){
        if (getLastMessage() != null && message.getMessageID().equals(getLastMessage().getMessageID()) && list.size() > 0) {
            setLastMessage(list.get(list.size() - 1));
        }
    }

    public void messageUnread(IMStruct002 message) {
        unReadCount += 1;
    }

    public void messageRead(IMStruct002 message) {
        if (unReadCount <= 0) return;
        unReadCount -= 1;
        updateSelfToDB();
    }

    public void unreadZero() {
        unReadCount = 0;
        updateSelfToDB();
    }

    private void updateSelfToDB() {
        JFMessageManager.messageModelDBManager.insertMessageModel(this);
    }

    private void update() {
        JFMessageManager.messageModelDBManager.insertMessageModel(this);
    }

    public List<IMStruct002> getList() {
        return list;
    }

    public void setList(List<IMStruct002> list) {
        this.list = list;
    }

    public Map<String, IMStruct002> getMap() {
        return map;
    }

    public void setMap(Map<String, IMStruct002> map) {
        this.map = map;
    }

    public int getUnReadCount() {
        return unReadCount;
    }

    public void setUnReadCount(int unReadCount) {
        this.unReadCount = unReadCount;
    }

    public int getUserType() {
        return userType;
    }

    public void setUserType(int userType) {
        this.userType = userType;
    }

    public String getUserID() {
        return userID;
    }

    public void setUserID(String userID) {
        this.userID = userID;
    }

    public IMStruct002 getLastMessage() {
        //todo yqs 为了保证聊天列表和对话界面的最后一条消息是同一个对象
        if (lastMessage != null) {
            if (map.containsKey(lastMessage.getMessageID())) {
                lastMessage = map.get(lastMessage.getMessageID());
            }

        }
        return lastMessage;
    }

    public void setLastMessage(IMStruct002 lastMessage) {
        this.lastMessage = lastMessage;
    }

    public String getAtMessageID() {
        return atMessageID;
    }

    public MessageModel setAtMessageID(String atMessageID) {
        this.atMessageID = atMessageID;
        return this;
    }
}
